package com.voja.salonschedule;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import com.voja.salonschedule.colorpicker.ColorPickerPreference;
import com.voja.salonschedule.data.Customer;
import com.voja.salonschedule.data.Event;
import com.voja.salonschedule.data.Event.EventItem;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.RemoteViews;

public class Widget extends AppWidgetProvider {

	public static final String ACTION_REFRESH_DATA = "ACTION_REFRESH_DATA";
	
	public static Context context;
	public static Resources res;
	
	public static class WidgetService extends Service {
		Context context;
		AppWidgetManager manager;
		ComponentName component;
		String packageName;
		
		@Override
		public IBinder onBind(Intent intent) {
			manager = AppWidgetManager.getInstance(this);
			component = new ComponentName(this, Index.class);
			int[] widgetIds = manager.getAppWidgetIds(component);
			packageName = this.getPackageName();
			
			for(int i=0; i<widgetIds.length; i++) {
				RemoteViews widget = new RemoteViews(packageName, R.layout.widget);
				loadItems(widget);
				manager.updateAppWidget(widgetIds[i], widget);
			}
			return null;
		}
		
	}
	
	@Override
	public void onUpdate(Context c, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		context = c;
		res = context.getResources();
		
		for (int i=0; i<appWidgetIds.length; i++) {
			Intent svcIntent = new Intent(context, WidgetService.class);
			
			svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
			svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
			
			// set bg color
			RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.widget);
			updateWidgetColors(widget);
			
			// load items
			loadItems(widget);
			
			// update widget
			appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
			
	    }
		
		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}
	
	public static void loadItems(RemoteViews widget) {
		Event model = new Event(context);
		ArrayList<EventItem> events = model.loadEvents(Calendar.getInstance().getTime(), true);
		
		widget.removeAllViews(R.id.items);
		
		Intent intent = new Intent(context, Index.class);
		PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
		widget.setOnClickPendingIntent(R.id.items, pIntent);
		
		Customer customerModel = new Customer(context);
		Bitmap bm;
		
		RemoteViews v;
		EventItem event;
		SimpleDateFormat timeFormat = Event.timeFormat;
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		String strTxtColor = ColorPickerPreference.convertToARGB(prefs.getInt("widget-color", Color.BLACK));
		int txtColor = Color.parseColor(strTxtColor);
		String strTimeColor = ColorPickerPreference.convertToARGB(prefs.getInt("widget-color-time", Color.BLACK));
		int txtTimeColor = Color.parseColor(strTimeColor);
		int separatorColor = Color.argb(50, Color.red(txtColor), Color.green(txtColor), Color.blue(txtColor));
		
        if (events.size()>0) {
        	for (int i=0; i<events.size(); i++) {
				event = events.get(i);
				
				v = new RemoteViews(context.getPackageName(), R.layout.widget_item);
				v.setTextViewText(R.id.txtTime, timeFormat.format(event.date_start));
				v.setTextViewText(R.id.txtCustomer, event.customer);
				v.setTextViewText(R.id.txtService, event.service);
				v.setTextViewText(R.id.txtEndTime, timeFormat.format(event.date_end));
				v.setInt(R.id.container, "setBackgroundColor", Color.TRANSPARENT);
				
				// colors
				v.setTextColor(R.id.txtCustomer, txtColor);
				v.setTextColor(R.id.txtService, txtColor);
				v.setTextColor(R.id.txtTime, txtTimeColor);
				v.setTextColor(R.id.txtEndTime, txtColor);
				v.setTextColor(R.id.txtTo, txtColor);
				v.setTextColor(R.id.txtEndTime, txtColor);
				v.setInt(R.id.separator, "setBackgroundColor", separatorColor);
				
				byte[] image = customerModel.getCustomer(event.customer).image;
				if (image != null && image.length>0) {
				    bm = BitmapFactory.decodeByteArray(image, 0, image.length);
				    v.setImageViewBitmap(R.id.imgCustomer, bm);
				}
				
				if (i>0) {
				    if (events.get(i-1).date_start.equals(event.date_start)) {
				        v.setViewVisibility(R.id.txtTime, View.INVISIBLE);
				        v.setViewVisibility(R.id.separator, View.GONE);
				    }
				} else {
					v.setViewVisibility(R.id.separator, View.GONE);
				}
				
				widget.addView(R.id.items, v);
			}
		} else {
			v = new RemoteViews(context.getPackageName(), R.layout.widget_item);
			if (res == null) {
			    res = context.getResources();
			}
			v.setTextViewText(R.id.txtCustomer, res.getString(R.string.NoEvents));
			v.setViewVisibility(R.id.txtTime, View.GONE);
			v.setViewVisibility(R.id.txtService, View.GONE);
			v.setViewVisibility(R.id.imgCustomer, View.GONE);
			v.setViewVisibility(R.id.txtTo, View.GONE);
			v.setViewVisibility(R.id.txtEndTime, View.GONE);
			v.setViewVisibility(R.id.separator, View.GONE);
			v.setInt(R.id.container, "setBackgroundColor", Color.TRANSPARENT);
			
			// colors
			v.setTextColor(R.id.txtCustomer, txtColor);
			
			widget.addView(R.id.items, v);
		}
	}
	
	public static void updateWidgets() {
	    if (context == null) {
	        return;
	    }
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		ComponentName component = new ComponentName(context, Widget.class);
		int[] widgetIds = manager.getAppWidgetIds(component);
		RemoteViews views;
		
		for (int i=0; i<widgetIds.length; i++) {
			views = new RemoteViews(context.getPackageName(), R.layout.widget);
			updateWidgetColors(views);
			loadItems(views);
			manager.updateAppWidget(widgetIds[i], views);
		}
	}
	
	public static void updateWidgetColors(RemoteViews views) {
	    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        
	    // widget background
	    String bgColor = ColorPickerPreference.convertToARGB(prefs.getInt("widget-background", Color.BLUE));
        views.setInt(R.id.items, "setBackgroundColor", Color.parseColor(bgColor));
	}
}
